<template>
    <div class="app-container">
        <el-form
            class="searchForm"
            ref="searchForm"
            :model="searchForm"
            :inline="true" size="mini" 
        >
            <el-form-item label="设备类型">
                <el-select
                    v-model="searchForm.equipTypeCode"
                    placeholder="请选择设备类型"
                    @change="equipTypeChange"
                    clearable
                >
                    <el-option
                        v-for="item in equipTypeList"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="部件">
                <el-select
                    multiple
                    clearable
                    :disabled="!searchForm.equipTypeCode"
                    v-model="searchForm.partTypes"
                    placeholder="请选择部件"
                >
                    <el-option
                        v-for="item in componentList"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="版本">
                <el-input clearable
                    v-model="searchForm.softwareVersion"
                    placeholder="请输入版本"
                />
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-search"
                    @click="doSearch"
                    >搜索</el-button
                >
                <el-button
                    type="default"
                    size="mini"
                    icon="el-icon-refresh"
                    @click="resetSearch"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>
        <div class="searchs-content">
            <el-button
                v-permission="['version:upgradetask:add']"
                type="primary"
                size="mini"
                plain
                icon="el-icon-plus"
                @click="addDialog"
                >新增</el-button
            >
        </div>
        <Table
            :tableHeader="tableHeader"
            :tableData="tableData"
            :tableLoading="listLoading"
        >
            <template slot="status" slot-scope="scope">
                <el-tag v-if="scope.row.status === 0" type="danger">{{
                    statusMap[scope.row.status]
                }}</el-tag>
                <el-tag v-else-if="scope.row.status === 1">{{
                    statusMap[scope.row.status]
                }}</el-tag>
                <el-tag v-else-if="scope.row.status === 2" type="success">{{
                    statusMap[scope.row.status]
                }}</el-tag>
            </template>
            <template slot="action" slot-scope="scope">
                <el-button
                    type="primary"
                    size="mini"
                    v-if="scope.row.status == 0"
                    @click="addDialog(scope.row)"
                    v-permission="['version:upgradetask:edit']"
                    >编辑</el-button
                >
                <el-button
                    type="warning"
                    size="mini"
                    @click="isDetail(scope.row)"
                    >详情</el-button
                >
                <el-button
                    type="danger"
                    size="mini"
                    v-if="scope.row.status == 0"
                    @click="isDelete(scope.row)"
                    v-permission="['version:upgradetask:remove']"
                    >删除</el-button
                >
            </template>
        </Table>
        <pagination
            v-if="total > 0"
            :total="total"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="fetchData"
        />

        <!-- 弹框 -->
        <Dialog
            :visible="visible"
            width="35%"
            :title="dialogTitle"
            @confirmDialog="confirmDialog"
            @cancelDialog="cancelDialog"
            class="visibleDialog"
        >
            <el-form
                class="dialog-form"
                ref="dialogForm"
                :model="dialogForm"
                label-width="140px" size="small"
                :rules="dialogRules"
            >
                <el-form-item label="自动升级文件选择" prop="softwareVersionId">
                    <el-select
                        class="ipt"
                        v-model="dialogForm.softwareVersionId"
                        placeholder="请选择升级文件" 
                        @change="updateFileChange" clearable
                    >
                        <el-option
                            v-for="item in updateOption"
                            :key="item.id"
                            :label="item.fileName"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="设备类型">
                    <el-input
                        class="ipt"
                        disabled
                        v-model="currentFile.equipTypeName"
                        placeholder="选择升级文件自动回显" clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="设备部件">
                    <el-input
                        class="ipt"
                        disabled
                        v-model="currentFile.partTypeName"
                        placeholder="选择升级文件自动回显" clearable
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="升级时间" prop="upgradeTime">
                    <el-date-picker
                        class="ipt datepicker"
                        :popper-append-to-body="false"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        format="yyyy-MM-dd HH:mm:ss"
                        v-model="dialogForm.upgradeTime"
                        type="datetime"
                        placeholder="选择升级时间" clearable
                    >
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="升级个数" prop="upgradeRule.count">
                    <el-input-number
                        class="ipt"
                        :min="1"
                        :max="50"
                        :step="1"
                        step-strictly
                        controls-position="right"
                        placeholder="请输入升级个数"
                        v-model="dialogForm.upgradeRule.count"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="间隔（分钟）" prop="upgradeRule.interval">
                    <el-input-number
                        class="ipt"
                        :min="1"
                        :max="60"
                        :step="1"
                        step-strictly
                        controls-position="right"
                        placeholder="请输入间隔"
                        v-model="dialogForm.upgradeRule.interval"
                    >
                    </el-input-number>
                    <!-- <span class="suffix">分钟</span> -->
                </el-form-item>
                <el-form-item label="任务说明">
                    <el-input
                        class="ipt"
                        type="textarea"
                        placeholder="请输入任务说明"
                        rows="5"
                        colum="3"
                        v-model="dialogForm.remark" 
                    ></el-input>
                </el-form-item>
            </el-form>
        </Dialog>

        <Dialog
            class="detail-dialog"
            :visible="detailVisible"
            width="80%"
            :isFullscreen="isDetailFullscreen"
            title="升级详情"
            :isFooter="false"
            @cancelDialog="detailCancelDialog"
        >
            <i
                class="el-icon-full-screen"
                @click="onFullscreen('isDetailFullscreen')"
            ></i>
            <div
                class="table-box"
                :style="{ 'max-height': isDetailFullscreen ? '78vh' : '60vh' }"
            >
                <Table
                    :tableHeader="detailTableHeader"
                    :tableData="detailTableData"
                    :tableLoading="detailListLoading"
                >
                    <template slot="softVersion" slot-scope="scope">
                        <span
                            style="text-align: left"
                            v-html="$options.filters.filterVersion(scope.row)"
                        ></span>
                    </template>
                    <template slot="compareVersion" slot-scope="scope">
                        <el-popover
                            placement="top-start"
                            width="200"
                            trigger="hover"
                            :content="`升级的版本与最新版本比较：${compareVersion(
                                scope.row
                            )}`"
                        >
                            <el-tag
                                slot="reference"
                                :type="
                                    compareVersion(scope.row).length == 2
                                        ? 'success'
                                        : 'danger'
                                "
                                >{{ compareVersion(scope.row) }}</el-tag
                            >
                        </el-popover>
                    </template>
                </Table>
            </div>
            <pagination
                v-if="detailTotal > 0"
                :total="detailTotal"
                :page.sync="detailForm.pageNum"
                :limit.sync="detailForm.pageSize"
                @pagination="getDetailData"
            />
        </Dialog>
    </div>
</template>

<script>
import { partType, softwareVersions } from "@/api/file";
import { equipType, equipment } from "@/api/factuer";

import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";

import moment from "moment";

import { handleConfirm } from "@/utils/messageBox";
import { removeNullUndefined } from "@/utils/index.js";
import { mapState } from "vuex";

export default {
    components: { Pagination, Table, Dialog },
    filters: {
        filterVersion(item) {
            // 转换后的二维数组
            if (
                item.equipSoftwareVersions &&
                item.equipSoftwareVersions.length > 0
            ) {
                let arrayTwo = Object.values(
                    item.equipSoftwareVersions.reduce((res, item) => {
                        res[item.partType]
                            ? res[item.partType].push(item)
                            : (res[item.partType] = [item]);
                        return res;
                    }, {})
                );
                let jsons = "";
                arrayTwo.map((item, index) => {
                    jsons += "<div>" + item[0].partTypeName + "：";
                    item.filter((qq, inx) => {
                        jsons +=
                            item.length > 1
                                ? `<span class="addrId">${qq.addrId}</span> ${qq.version}；`
                                : qq.version;
                    });
                    jsons += "</div>";
                });
                return jsons;
            } else {
                return "";
            }
        },
    },
    data() {
        return {
            list: null,
            listLoading: false,
            detailListLoading: true,
            total: 0,
            searchForm: {
                pageNum: 1,
                pageSize: 15,
                equipTypeCode: "",
                partTypes: [],
                softwareVersion: "",
            },
            detailForm: {
                pageNum: 1,
                pageSize: 15,
            },
            statusMap: {
                0: "未开始",
                1: "进行中",
                2: "已完成",
            },

            tableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "60",
                    fixed: true,
                },
                {
                    label: "设备类型",
                    prop: "equipTypeName",
                },
                {
                    label: "部件",
                    prop: "partTypeName",
                },
                {
                    label: "类型",
                    prop: "type",
                    formatter: (item) => {
                        let classify =
                            this.enumsJson.EQUIP_UPGRADE_TASK_TYPE.find((p) => {
                                return p.code == item.type;
                            });
                        return classify != undefined
                            ? classify.label
                            : item.type;
                    },
                },
                {
                    label: "版本",
                    prop: "softwareVersion",
                },
                { slot: "status", label: "执行情况" },
                {
                    label: "创建时间",
                    prop: "createTime",
                    width:"100"
                },
                {
                    label: "创建人",
                    prop: "createBy",
                },
                { slot: "action", label: "操作", width: "230px" },
            ],
            detailTableHeader: [
                {
                    type: "index",
                    label: "序号",
                    width: "50",
                    fixed: true,
                },
                {
                    label: "设备编码",
                    prop: "equipCode",
                    wide: "190",
                },

                {
                    label: "响应状态",
                    prop: "result",
                    formatter: (item) => {
                        return item.result || item.result == 0
                            ? this.enumsJson.LOG_STATUS.find(
                                  (pp) => pp.code == item.result
                              ).label
                            : "";
                    },
                    wide: "78",
                },
                { slot: "softVersion", label: "最新版本" },
                {
                    label: "比较",
                    slot: "compareVersion",
                    width: "80",
                },
                {
                    label: "上报时间",
                    prop: "reportTime",
                    formatter: (item) => {
                        return item.reportTime
                            ? moment(item.reportTime).format(
                                  "YYYY-MM-DD HH:mm:ss"
                              )
                            : "";
                    },
                    wide: "155",
                },
            ],
            tableData: [],
            detailTableData: [],
            detailTotal: 0,
            visible: false, //弹框标识
            dialogForm: {
                softwareVersionId: "",
                remark: "",
                partType: "",
                equipTypeCode: "",
                upgradeTime: "",
                upgradeRule: {
                    count: 1,
                    interval: 1,
                },
            },
            dialogRules: {
                softwareVersionId: [
                    {
                        required: true,
                        message: "请选择升级文件",
                        trigger: "change",
                    },
                ],
                upgradeTime: [
                    {
                        required: true,
                        message: "请选择升级时间",
                        trigger: "change",
                    },
                ],
                "upgradeRule.count": [
                    {
                        required: true,
                        message: "请输入升级个数",
                        trigger: "blur",
                    },
                ],
                "upgradeRule.interval": [
                    {
                        required: true,
                        message: "请输入升级间隔",
                        trigger: "blur",
                    },
                ],
            },
            dialogTitle: "",

            detailVisible: false,
            updateOption: [],
            equipTypeList: [],
            componentList: [],
            dialogComponentList: [],
            currentRow: {},
            currentFile: {
                equipTypeName: "",
                partTypeName: "",
            },
            isDetailFullscreen: true,
        };
    },
    watch: {
        // "dialogForm.equipTypeCode": {
        //   handler(newVal, oldVal) {
        //     if (newVal) {
        //       this.dialogEquipChange(newVal);
        //     }
        //   },
        //   immediate: true,
        // },
    },
    computed: {
        ...mapState({
            enumsJson: (state) => state.enums.enums,
        }),
    },
    created() {
        this.fetchData();
        this.getUpgradeList();
        this.getEquipType();
    },
    methods: {
        fetchData(val) {
            this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
            this.listLoading = true;
            equipment(
                "/upgrade/task/list",
                "post",
                {
                    ...removeNullUndefined(this.searchForm),
                    type: "SCHEDULE",
                },
                1
            )
                .then((res) => {
                    this.tableData = res.data;
                    this.total = +res.total;

                    this.searchForm.pageNum = +res.pageNum;
                })
                .finally(() => {
                    this.listLoading = false;
                });
        },
        async getEquipType() {
            let data = await equipType("/datails", "post");
            this.equipTypeList = data.data;
        },
        async equipTypeChange(e) {
            this.componentList = [];
            this.searchForm.partTypes = [];
            if (e) {
                let data = await partType("/list", "get", { equipTypeCode: e });
                this.componentList = data.data;
            }
        },
        async dialogEquipChange(e) {
            let data = await partType("/list", "get", { equipTypeCode: e });
            this.dialogComponentList = data.data;
        },
        getUpgradeList() {
            softwareVersions("/autoupgrade/all", "get").then((res) => {
                this.updateOption = res.data;
            });
        },
        // 弹框取消
        cancelDialog() {
            this.visible = false;
            this.resetDialogForm("dialogForm");
            this.dialogForm = {
                softwareVersionId: "",
                remark: "",
                partType: "",
                equipTypeCode: "",
                upgradeTime: "",
                upgradeRule: {
                    count: 1,
                    interval: 1,
                },
            };
            this.currentFile = {
                equipTypeName: "",
                partTypeName: "",
            };
        },
        // 弹框确认
        confirmDialog() {
            this.submitDialogForm("dialogForm");
        },
        // 新增
        addDialog(row) {
            this.visible = true;
            if (row.id) {
                this.currentRow = { ...row };
                let { equipTypeName, partTypeName } = row;
                this.currentFile = { equipTypeName, partTypeName };
                let {
                    id,
                    softwareVersionId,
                    remark,
                    partType,
                    equipTypeCode,
                    upgradeTime,
                    upgradeRule,
                } = row;
                let uprule = JSON.parse(upgradeRule);
                this.dialogForm = {
                    id,
                    softwareVersionId,
                    remark,
                    partType,
                    equipTypeCode,
                    upgradeTime,
                    upgradeRule: {
                        count: uprule.count ? uprule.count : undefined,
                        interval: uprule.interval ? uprule.interval : undefined,
                    },
                };
                this.dialogTitle = "编辑";
            } else {
                this.currentRow = {};
                this.dialogTitle = "新增";
            }
        },
        submitDialogForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let msg = this.dialogForm.id ? "编辑" : "新增";
                    handleConfirm(`确定要${msg}吗？`, "warning", "提示")
                        .then((res) => {
                            this.isAddUpdate();
                        })
                        .catch((err) => {
                            // do something cancel
                        });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetDialogForm(formName) {
            this.$refs[formName].resetFields();
        },
        // 新增
        isAddUpdate() {
            let param = { ...this.dialogForm };
            let url = this.currentRow.id
                ? `/upgrade/task/update/${this.currentRow.id}`
                : "/upgrade/task/insert";
            equipment(url, "post", param, 1).then((res) => {
                if (res.code == 200) {
                    this.visible = false;
                    this.$message.success(res.message);
                    this.fetchData();
                }
            });
        },
        isDelete(row) {
            handleConfirm(
                "删除后不可恢复，确定执行此操作吗？",
                "warning",
                "提示"
            )
                .then((res) => {
                    this.doDelete(row);
                })
                .catch((err) => {
                    // do something cancel
                });
        },
        doDelete(row) {
            equipment(`/upgrade/task/delete/${row.id}`, "post").then((res) => {
                if (res.code == 200) {
                    this.$message.success(res.message);
                    this.fetchData();
                }
            });
        },
        isDetail(row) {
            this.detailVisible = true;
            this.currentRow = row;
            this.getDetailData();
        },
        getDetailData() {
            this.detailListLoading = true;
            this.detailTableData = [];
            this.detailTotal = 0;
            equipment("/upgrade/log", "get", {
                ...this.detailForm,
                taskId: this.currentRow.id,
            })
                .then((res) => {
                    this.detailTableData = res.data ? res.data : [];
                    this.detailTotal = res.total ? +res.total : 0;
                })
                .finally(() => {
                    this.detailListLoading = false;
                });
        },
        detailCancelDialog() {
            this.detailTableData = [];
            this.detailTotal = 0;
            this.detailForm = {
                pageNum: 1,
                pageSize: 15,
            };
            this.detailVisible = false;
            this.isDetailFullscreen = true;
        },
        updateFileChange(e) {
            let current = this.updateOption.find((item) => item.id == e);
            let { equipTypeName, partTypeName } = current;
            this.currentFile = { equipTypeName, partTypeName };
            this.dialogForm.equipTypeCode = current.equipTypeCode;
            this.dialogForm.partType = current.partType;
        },
        // 搜索重置
        resetSearch() {
            this.searchForm = {
                pageNum: this.searchForm.pageNum,
                pageSize: this.searchForm.pageSize,
                equipTypeCode: "",
                partTypes: [],
                softwareVersion: "",
            };
        },
        doSearch() {
            this.searchForm.pageNum = 1;
            this.fetchData();
        },
        onFullscreen(val) {
            this[val] = !this[val];
        },
        compareVersion(item) {
            let every = item.equipSoftwareVersions.every(item=>{
                return item.version == this.currentRow.softwareVersion;
            });
            if (every) {
                return "一致";
            }
            return "不一致";
        },
    },
};
</script>
<style lang="scss" scoped>
.searchForm {
    padding-left: 8px;
    .el-form-item {
        margin-bottom: 8px;
    }
}
.dialog-form {
    .el-select,
    .el-input,
    .el-input-number {
        width: 92%;
    }

    .el-textarea {
        width: 92%;
    }
}

.el-date-editor {
    width: 92%;
}

::v-deep .addrId {
    display: inline-block;
    width: 16px;
    height: 16px;
    line-height: 15px;
    font-size: 12px;
    border-radius: 50%;
    text-align: center;
    border: 1px solid #606266;
    transform: scale(0.95);
}
.detail-dialog {
    .table-box {
        overflow-y: scroll;
    }

    ::v-deep .el-table__empty-block {
        min-height: 160px;
    }
}
.visibleDialog {
    ::v-deep .el-dialog__footer {
        padding-top: 0;
    }
}
.el-icon-full-screen {
    position: absolute;
    right: 45px;
    color: rgb(144, 147, 153);
    cursor: pointer;
    font-size: 22px;
    display: inline-block;
    margin-top: -44px;
    font-weight: bold;
}
</style>
